##通过xtquant订阅行情,获得历史数据和tick数据
##存储到本地json
##tick发送到消息队列

from xtquant import xtdata
from typing import List
from 新版2.系统组件.基础配置 import settings
from 新版2.行情数据.本地存储 import stock_saver
from 新版2.行情数据.Tick推送 import stock_saver_mq


class MarketMonitor:
    def __init__(self):
        stock_items = settings.STOCK_CODE
        self.period = "tick"
        self.stock_codes: List[str] = [
            str(item.get("all_code"))
            for item in stock_items
            if isinstance(item, dict) and item.get("all_code")
        ] if isinstance(stock_items, list) else []
        self.stock_type = {stock["all_code"]: stock["name"] for stock in stock_items}
        self._running = False

    ##订阅tick回调
    def quote_callback(self, data):
        for stock_code, stock_data in data.items():
            if not stock_data:
                continue
            ##这里把stock_code也放入stock_data
            stock_data[0]["stock_code"] = stock_code
            ##保存入本地json
            stock_saver.save_tick(stock_code,stock_data)
            ##推送至消息队列
            stock_saver_mq.save_tick(stock_code,stock_data)

    ##启动
    def start(self):
        print(f"开启实时行情")
        self._running = True

        # 订阅实时行情
        for code in self.stock_codes:
            xtdata.subscribe_quote(
                code,
                period=self.period,
                count=-1,
                callback=self.quote_callback
            )
            print(f"已订阅 {code} 的实时行情")
        print(f"开始监听 {len(self.stock_codes)} 只股票的实时行情...")

        try:
            xtdata.run()  # 阻塞
        except KeyboardInterrupt:
            print("行情监控已手动停止")
        except Exception as e:
            print(f"行情监控异常: {e}")

    ##停止
    def stop(self):
        self._running = False
        print("行情监控已停止")

if __name__ == "__main__":
    # 创建保存器（每5条或每秒自动刷新）
    read = MarketMonitor()
    read.start()